/* eslint-disable react-hooks/exhaustive-deps */
/**
 * 组合概览页
 * @author gf
 */
import {
  createRef,
  forwardRef,
  Fragment,
  useCallback,
  useEffect,
  useImperativeHandle,
  useState,
} from "react";
import styles from "./index.less";
import {
  DatePicker,
  Select,
  Spin,
  Table,
  Tabs,
  Tooltip,
  TreeSelect,
} from "antd";
import cn from "classnames";
import {
  getUrlParam,
  transferToText,
  isAuthored,
  listenScroll,
} from "@/utils/utils";
import FofButton from "@/components/Button/fofButton";
import icon_detail from "@/assets/icons/icon-jump-detail.png";
import icon_enlarge from "@/assets/icons/icon-enlarge.png";
import icon_review from "@/assets/icons/icon-review.png";
import ButtonNoBorder from "@/components/Button/buttonNoBorder";
import EventLine from "@/components/EchartsComponents/Line/EventLine";
import { indicatorColumns } from "./columns";
import {
  queryFundEventList,
  queryPortfolioEventList,
  portfolio_comment,
  update_portfolio_comment,
  fof_portfolio_basic,
  queryPortfolioFundList,
  queryFundByEventType,
  query_profit_and_benchmark,
  get_main_and_benchmark,
  get_return_and_risk,
  queryUserHeadImg,
} from "./portfolio";
import UploadFileModal from "@/components/UploadFileModal";
import TextEditor from "@/components/TinyEditor";
import FundList from "./components/FundList";
import styled from "styled-components";
import dayjs from 'dayjs';
import { Title } from "@/components/Title";
import { PageWrapper } from "@/components/PageWrapper";
import ActiveContext from "@/components/Button/ActiveContext";
import SingleCheck from "@/components/CheckBox";
import * as _ from "lodash";
import { useNavigate } from "react-router-dom";
import icon_avatar from "@/assets/icons/avatar.png";
import EventEmpty from "@/components/FOF/EventEmpty";

const { TabPane } = Tabs;
const portfolioCode = getUrlParam("id");
const name = decodeURIComponent(getUrlParam("name"));
export const toFixedTwo = (num: number) => {
  return _.isNumber(num) ? (num * 100).toFixed(2) + "%" : "-";
};
interface RenderDescProps {
  className?: string;
  hideCompare?: boolean;
  setPortfolioInfo?: (p: any) => void;
}

interface ReviewProps {
  setRightReview: (p: any) => void;
  queryLatestTime: () => void;
}
const DatePickerWrapper = styled.div`
  .ant-picker {
    width: 100%;
    padding: 2px 11px 2px;
    border-color: #d4d7dd;
    input {
      color: #35425e;
      font-size: 13px;
    }
    input::placeholder {
      opacity: 0.4;
    }
  }
`;

const RenderDescOverview = forwardRef((props: RenderDescProps, ref: any) => {
  const [info, setInfo] = useState<any>({});
  let navigate = useNavigate();
  const handleQueryDesc = () => {
    fof_portfolio_basic({ portfolioCode }).then((res: any) => {
      if (res?.code === "0") {
        setInfo(res?.data);
        props.setPortfolioInfo(res?.data);
      }
    });
  };
  useEffect(() => {
    if (portfolioCode) {
      handleQueryDesc();
    }
  }, [portfolioCode, name]);

  useImperativeHandle(ref, () => ({
    query: () => {
      handleQueryDesc();
    },
  }));

  return (
    <div className={cn(styles.boxBorder, styles.borderBgc)}>
      <FofButton text={info?.portfolioName || "-"} className={styles.title} />
      <div className={styles.compare}>
        {
          <Fragment>
            <div className={styles.compare_text} title={info?.perfComBenchmark}>
              业绩比较基准：{info?.perfComBenchmark || "-"}
            </div>
            <div className={styles.compare_button}>
              <ButtonNoBorder
                src={icon_detail}
                text="历史调仓记录"
                onClick={() => {
                  let url = `/change-position?id=${portfolioCode}&name=${name}`;
                  process.env.NODE_ENV !== "production"
                    ? navigate(url)
                    : top.window.postMessage(
                        {
                          url: `/desert-star${url}`,
                        },
                        location.origin
                      );
                }}
              />
            </div>
          </Fragment>
        }
        <div className={styles.footer}>
          <div className={styles.footer_date}>
            <span>组合成立时间</span>
            <span>{info?.establishDate || "-"}</span>
          </div>
          <div className={styles.footer_date}>
            <span>数据更新时间</span>
            <span>{info?.dataUpdateDate || "-"}</span>
          </div>
          <div className={styles.footer_date}>
            <span>最新点评时间</span>
            <span>{info?.commentDate || "-"}</span>
          </div>
        </div>
      </div>
    </div>
  );
});

export const Review = (props: ReviewProps) => {
  const { setRightReview, queryLatestTime } = props;
  const [reviewInfo, setReviewInfo] = useState({});
  const [editContent, setEditContent] = useState("");
  const [date, setDate] = useState(dayjs());
  const [avatar, setAvatar] = useState("");
  const [errorList, setErrorList] = useState([]);
  const [modalRecord, setModalRecord] = useState({
    visible: false,
    title: "调整点评",
  });
  const [loadingSubmit, setLoadingSubmit] = useState(false);

  // 查询你点评
  const handleQueryComment = () => {
    portfolio_comment({ portfolioCode }).then((res) => {
      if (res?.code === "0") {
        setReviewInfo(res?.data);
        setRightReview(res?.data);
      } else {
        setReviewInfo({});
        setRightReview({});
      }
    });
  };

  const handleChangeDate = (e) => {
    setDate(e);
    if (e) {
      setErrorList((state) => {
        return state.filter((v) => v !== "updateTime");
      });
    }
  };

  // 提交点评
  const handleSubmitReview = () => {
    setLoadingSubmit(true);
    let arr: string[] = [];
    if (!editContent) {
      arr.push("comment");
    }
    if (!date) {
      arr.push("updateTime");
    }
    if (arr.length > 0) {
      setErrorList(arr);
      return;
    }
    update_portfolio_comment({
      author: reviewInfo?.author,
      comment: editContent,
      id: reviewInfo?.id,
      portfolioCode,
      updatedTime: dayjs(date).format("YYYY/MM/DD"),
    }).then((res) => {
      setLoadingSubmit(false);
      if (res?.code === "0") {
        setModalRecord({
          visible: false,
          title: "调整点评",
        });
        handleQueryComment();
        queryLatestTime();
      }
    });
  };

  useEffect(() => {
    if (!modalRecord.visible) {
      setDate(null);
      setEditContent("");
      setErrorList([]);
    }
  }, [modalRecord.visible]);

  // 获取头像
  const handleQueryAvatar = () => {
    queryUserHeadImg({ userId: reviewInfo.authorId }).then((res) => {
      if (res?.code === "0") {
        if (res?.data?.imgType) {
          setAvatar(
            `data:image/${res?.data?.imgType};base64,${res?.data.base64Str}`
          );
        } else {
          setAvatar(icon_avatar);
        }
      }
    });
  };

  useEffect(() => {
    handleQueryComment();
    // handleQueryAvatar();
  }, []);

  useEffect(() => {
    if (reviewInfo.authorId) {
      handleQueryAvatar();
    }
  }, [reviewInfo.authorId]);

  // 无内容，可点评
  const _renderSkeleton = () => {
    return (
      <div className={styles.skeleton}>
        <div>
          <div></div>
          {isAuthored("EDIT_REVIEW") && (
            <span
              onClick={() =>
                setModalRecord((state) => {
                  return {
                    visible: true,
                    title: "调整点评",
                  };
                })
              }
            >
              调整点评
              <img src={icon_review} alt="review" />
            </span>
          )}
        </div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
      </div>
    );
  };

  return !isAuthored("EDIT_REVIEW") &&
    !reviewInfo?.author &&
    !reviewInfo?.comment ? null : (
    <div className={cn(styles.boxBorder, styles.review)}>
      <UploadFileModal
        title={modalRecord.title}
        okText="提交"
        bodyStyle={{
          paddingBottom: 16,
          paddingRight: 37,
          marginRight: 8,
          maxHeight: "calc(100vh - 200px)",
          overflowY: "scroll",
        }}
        footerHide={modalRecord.title === "综合点评"}
        visible={modalRecord.visible}
        toggleModal={(b: boolean) => {
          setModalRecord((state) => {
            return {
              ...state,
              visible: b,
            };
          });
        }}
        handleOk={handleSubmitReview}
        loading={loadingSubmit}
      >
        <div>
          {modalRecord.title === "综合点评" ? (
            <div style={{ display: "flex" }}>
              <div className={styles.review_avatar} style={{ marginTop: 0 }}>
                <img src={avatar} alt="avatar" />
              </div>
              <div style={{ marginTop: 10 }}>
                <div className={styles.review_right_top_left}>
                  <span>综合点评 - {reviewInfo?.author || "-"}</span>
                  <span>{reviewInfo?.updatedTime || "-"}</span>
                </div>
                <div
                  className={cn(styles.content, "editor-description")}
                  dangerouslySetInnerHTML={{
                    __html: reviewInfo?.comment || "--",
                  }}
                />
              </div>
            </div>
          ) : (
            <Fragment>
              <div className={cn(styles.portFolioReview)}>
                <span
                  className={cn(styles.portFolioReview_label, styles.required)}
                >
                  日期
                </span>
                <DatePickerWrapper>
                  <DatePicker
                    disabledDate={(currentDate) => {
                      return dayjs(currentDate) > dayjs(Date.now());
                    }}
                    onChange={handleChangeDate}
                    value={date}
                    className={errorList.includes("updateTime") && "form_error"}
                  />
                </DatePickerWrapper>
              </div>
              <div
                className={cn(styles.portFolioReview)}
                style={{ marginTop: 8 }}
              >
                <span
                  className={cn(styles.portFolioReview_label, styles.required)}
                >
                  内容
                </span>
                <TextEditor
                  isError={errorList.includes("comment")}
                  editorKey="change-review"
                  content={editContent}
                  onContentChange={(e) => {
                    if (e) {
                      setErrorList((state) => {
                        return state.filter((v) => v !== "comment");
                      });
                    }
                    setEditContent(e);
                  }}
                />
              </div>
            </Fragment>
          )}
        </div>
      </UploadFileModal>
      {!reviewInfo?.author && !reviewInfo?.comment ? (
        <div className={cn(styles.review_avatar, styles.review_placeholder)} />
      ) : (
        <div className={styles.review_avatar}>
          <img src={avatar} alt="avatar" />
        </div>
      )}
      {!reviewInfo?.author && !reviewInfo?.comment ? (
        _renderSkeleton()
      ) : (
        <div className={styles.review_right}>
          <div className={styles.review_right_top}>
            <div className={styles.review_right_top_left}>
              <span>综合点评 - {reviewInfo?.author}</span>
              <span>{reviewInfo?.updatedTime}</span>
              {isAuthored("EDIT_REVIEW") && (
                <span
                  onClick={() => {
                    setModalRecord((state) => {
                      return {
                        visible: true,
                        title: "调整点评",
                      };
                    });
                    setDate(dayjs(reviewInfo?.updatedTime));
                    setEditContent(reviewInfo?.comment);
                  }}
                >
                  调整点评
                  <img src={icon_review} alt="review" />
                </span>
              )}
            </div>
            <div
              className={styles.review_right_top_right}
              onClick={() =>
                setModalRecord((state) => {
                  return {
                    visible: true,
                    title: "综合点评",
                  };
                })
              }
            >
              <img src={icon_enlarge} alt="enlarge" />
            </div>
          </div>
          <div
            className={styles.review_right_bottom}
            onDoubleClick={() => {
              setModalRecord((state) => {
                return {
                  visible: true,
                  title: "综合点评",
                };
              });
            }}
          >
            <span>
              {transferToText(reviewInfo?.comment)
                ?.replaceAll("&nbsp;", "")
                ?.replaceAll("&gt;", ">")
                ?.replaceAll("&lt", "<")
                ?.replaceAll("&ldquo;", '"')
                ?.replaceAll("&rdquo;", '"')}
            </span>
          </div>
        </div>
      )}
    </div>
  );
};

const PortfolioOverview = (props: any) => {
  let navigate = useNavigate();
  type ObjectT = {
    [key: string]: string;
  };
  const refOverviewDesc = createRef();
  const [portfolioInfo, setPortfolioInfo] = useState<any>({});
  const [fundList, setFundList] = useState([]);
  const [xAxis, setXAxis] = useState([]);
  const [legend, setLegend] = useState([]);
  const [yAxis, setYAxis] = useState([]);
  const [chartTitle, setChartTitle] = useState<ObjectT>({});
  const [checkedEvents, setCheckedEvents] = useState([]);
  const [loadingEvent, setLoadingEvent] = useState(false);
  const [sigParams, setSigParams] = useState({
    eventCode: "",
    id: "",
    innerCode: "",
  });
  const [time, setTime] = useState(Date.now());
  const [curTab, setCurTab] = useState("1");
  const [tableData, setTableData] = useState([]);
  const [rightReveiw, setRightReview] = useState<ObjectT>({});
  // const [selectedRow, setSelectedRow] = useState();
  const PATCH_TEXT = "PATCH_TEXT";
  const handleChangeChecked = (record: any) => {
    const copyCheckedEvents = _.cloneDeep(checkedEvents);
    const i = copyCheckedEvents.findIndex((l) => l.id === record.id);
    if (i === -1) {
      copyCheckedEvents.push(record);
    } else {
      copyCheckedEvents.splice(i, 1);
    }
    setCheckedEvents(copyCheckedEvents);
    // handleChangeLineData(copyCheckedEvents)
  };

  // 点开单基事件
  const handleClickSigEvent = (e: any) => {
    setSigParams({
      eventCode: e.eventCode,
      id: e.id,
      innerCode: e.innerCode,
    });
    setTime(Date.now());
  };
  const renderT = (text, record) =>
    record.eventDate === PATCH_TEXT ? null : text || "-";

  const combinationColumns = [
    {
      title: "日期",
      dataIndex: "eventDate",
      key: "eventDate",
      width: 85,
      render: (text) =>
        text === PATCH_TEXT ? null : (
          <span>{dayjs(text).format("YYYY/MM/DD")}</span>
        ),
    },
    {
      title: "事件类型",
      dataIndex: "eventName",
      key: "eventName",
      ellipsis: true,
      width: 185,
      render: (text: string, records: any) => (
        <Tooltip
          overlayClassName={styles.cusToolTip}
          placement="topLeft"
          title={records?.dataMemo}
        >
          {renderT(text, records)}
        </Tooltip>
      ),
    },
    {
      title: "内容",
      dataIndex: "eventHeader",
      key: "eventHeader",
      ellipsis: true,
      width: 185,
      render: (text: string, record: ObjectT) =>
        [
          "portfolio_deviation_from_benchmark_negative",
          "portfolio_deviation_from_benchmark_positive",
        ].includes(record.eventCode) ? (
          <span>{renderT(text, record)}</span>
        ) : (
          <ActiveContext
            onClick={() => {
              let url =
                (record?.eventCode === "portfolio_asset_allocation_alert"
                  ? "/overall-feature"
                  : record?.eventCode === "portfolio_position_change"
                  ? "/change-position"
                  : "/stock-asset-feature") +
                // eslint-disable-next-line no-restricted-globals
                `?id=${portfolioCode}&eventId=${record.id}&eventCode=${
                  record.eventCode
                }&name=${name}&time=${Date.now()}&positionDate=${
                  record.eventDate
                }`;
              process.env.NODE_ENV !== "production"
                ? navigate(url)
                : top.window.postMessage(
                    {
                      url: `/desert-star${url}`,
                    },
                    location.origin
                  );
            }}
          >
            {renderT(text, record)}
          </ActiveContext>
        ),
    },
    {
      title: "在图上标出",
      align: "center",
      width: 60,
      render: (text: string, record: ObjectT) =>
        record.eventDate === PATCH_TEXT ? null : (
          <SingleCheck
            checked={
              checkedEvents.findIndex((v) => v.id === record.id) > -1
                ? true
                : false
            }
            style={{ position: "relative", top: "-1px" }}
            onClick={() => handleChangeChecked(record)}
          />
        ),
    },
  ];

  const singleColumns = [
    {
      title: "日期",
      dataIndex: "eventDate",
      key: "eventDate",
      width: 80,
      render: (text) =>
        text === PATCH_TEXT ? null : (
          <span>{dayjs(text).format("YYYY/MM/DD")}</span>
        ),
    },
    {
      title: "关联基金名称（代码）",
      dataIndex: "eventType",
      key: "eventType",
      ellipsis: true,
      width: 150,
      render: (text?: string, records: any) => {
        return (
          <span>
            {records.eventDate === PATCH_TEXT
              ? null
              : `${records?.secuAbbr || "-"}(${records?.secuCode || "-"})`}
          </span>
        );
      },
    },
    {
      title: "事件类型",
      dataIndex: "eventName",
      key: "eventName",
      ellipsis: true,
      width: 120,
      render: (text?: string, records: any) => (
        <Tooltip
          overlayClassName={styles.cusToolTip}
          placement="topLeft"
          title={records?.dataMemo}
        >
          {renderT(text, records)}
        </Tooltip>
      ),
    },
    {
      title: "内容",
      dataIndex: "eventHeader",
      key: "eventHeader",
      ellipsis: true,
      width: 150,
      render: (text: string, record: any) => (
        <ActiveContext
          style={{ paddingRight: 4 }}
          onClick={() => handleClickSigEvent(record)}
        >
          {renderT(text, record)}
        </ActiveContext>
      ),
    },
  ];

  useEffect(() => {
    // 查询关联基金列表
    queryPortfolioFundList({ portfolioCode }).then((res: any) => {
      if (res?.code === "0") {
        setFundList(res?.data);
      }
    });
  }, []);

  useEffect(() => {
    handleChangeLineData(checkedEvents, yAxis);
  }, [checkedEvents, xAxis]);

  // 修改折线图数据
  const handleChangeLineData = (checkes: any[], yData?: any) => {
    const keyContent = {};
    checkes.map((v) => {
      if (keyContent[v.eventDate]) {
        keyContent[v.eventDate] =
          keyContent[v.eventDate] + ";\n" + v.eventHeader;
      } else {
        keyContent[v.eventDate] = v.eventHeader;
      }
    });
    const data = _.cloneDeep(yData);
    const arr = [];
    data.map((v) => {
      if (v.label === portfolioInfo.portfolioName) {
        v.value.map((m, i) => {
          if (keyContent[m.key]) {
            m.content = keyContent[m.key];
            arr.push({
              key: m.key,
              title: m.content,
            });
          } else {
            m.content = "";
          }
        });
      }
    });
    setYAxis(data);
  };

  useEffect(() => {
    if (portfolioInfo?.establishDate) {
      setLoadingEvent(true);
      query_profit_and_benchmark({
        // beginDate:portfolioInfo?.establishDate,
        // endDate:,
        portfolioCode,
      }).then((res: any) => {
        setLoadingEvent(false);
        if (res?.code === "0") {
          setXAxis(res?.data?.xaxis);
          if (res?.data?.yaxis[0]?.label === portfolioInfo.portfolioName) {
            res?.data?.yaxis.reverse();
            setYAxis(res?.data?.yaxis);
            setLegend(res?.data?.yaxis.map((v) => v.label));
          } else {
            setYAxis(res?.data?.yaxis);
            setLegend(res?.data?.yaxis.map((v) => v.label));
          }

          setChartTitle({
            title: res.data.titles,
            endDate: dayjs(res.data.endDate).format("YYYY/MM/DD"),
            startDate: dayjs(res.data.startDate).format("YYYY/MM/DD"),
          });
        }
      });
    }
  }, [portfolioInfo.establishDate]);

  // 渲染图和tab图
  const _renderTab = () => {
    const [curTab, setCurTab] = useState("1");
    const [bColumns, setBcolumns] = useState([
      {
        title: "指标",
        dataIndex: "name",
        key: "name",
        width: 110,
        ellipsis: true,
        render: (text?: string) => text || "-",
      },
      {
        title: "近3月收益",
        dataIndex: "近3月收益",
        key: "近3月收益",
        align: "right",
        width: 51,
        render: (text?: number) => toFixedTwo(text),
      },
      {
        title: "近6月收益",
        dataIndex: "近6月收益",
        key: "近6月收益",
        align: "right",
        width: 51,
        render: (text?: number) => toFixedTwo(text),
      },
      {
        title: "近一年收益",
        dataIndex: "近一年收益",
        key: "近一年收益",
        align: "right",
        width: 60,
        render: (text?: number) => toFixedTwo(text),
      },
      {
        title: "近三年收益",
        dataIndex: "近三年收益",
        key: "近三年收益",
        align: "right",
        width: 60,
        render: (text?: number) => toFixedTwo(text),
      },
      {
        title: "今年以来",
        dataIndex: "今年以来",
        key: "今年以来",
        align: "right",
        width: 50,
        render: (text?: number) => toFixedTwo(text),
      },
    ]);
    const [bData, setBdata] = useState([]);
    const [loadingBdata, setLoadingBdata] = useState(false);
    const [indicatorData, setIndicatorData] = useState([]);
    const [loadingIndicatorData, setLoadingIndicatorData] = useState(false);
    const callback = (key: string) => {
      setCurTab(key);
    };

    const handleQueryRisk = () => {
      setLoadingIndicatorData(true);
      get_return_and_risk({
        beginDate: dayjs(portfolioInfo?.establishDate).format("YYYY-MM-DD"),
        endDate: dayjs().subtract(1, "days").format("YYYY-MM-DD"),
        portfolioCode,
        benchmarkCode: portfolioInfo?.benchmarkCode,
      }).then((res: any) => {
        setLoadingIndicatorData(false);
        if (res?.code === "0") {
          setIndicatorData(res?.data?.indicators?.table || []);

          const { year1, year2, table } = res?.data?.intervalEarningsRet || {};
          if (year1 && year2 && bColumns.length === 6) {
            setBcolumns((state) => {
              const arr = [
                {
                  title: year1,
                  dataIndex: year1,
                  key: year1,
                  align: "right",
                  width: 50,
                  render: (text?: string) => toFixedTwo(text),
                },
                {
                  title: year2,
                  dataIndex: year2,
                  key: year2,
                  align: "right",
                  width: 50,
                  render: (text?: string) => toFixedTwo(text),
                },
                {
                  title: "成立以来",
                  dataIndex: "成立以来",
                  key: "成立以来",
                  align: "right",
                  width: 50,
                  render: (text?: string) => toFixedTwo(text),
                },
              ];
              return [...state, ...arr];
            });
            setBdata(table);
          }
        } else {
          setIndicatorData([]);
        }
      });
    };

    useEffect(() => {
      if (!portfolioInfo?.benchmarkCode) return;
      handleQueryRisk();
    }, [portfolioInfo?.benchmarkCode]);

    return (
      <Tabs className={styles.cusTab} activeKey={curTab} onChange={callback}>
        <TabPane tab="绩效指标" key="1">
          <Table
            className={cn(styles.cusTable, styles.littleTable)}
            loading={loadingIndicatorData}
            columns={indicatorColumns}
            rowKey={(r) => r.indicator}
            dataSource={indicatorData}
            pagination={false}
            // scroll={{x:510}}
          />
        </TabPane>
        <TabPane tab="区间收益" key="2">
          <Table
            className={cn(styles.cusTable, styles.littleTable)}
            loading={loadingBdata}
            columns={bColumns}
            rowKey={(r) => r.name}
            dataSource={bData}
            pagination={false}
            // scroll={{x:544}}
          />
        </TabPane>
      </Tabs>
    );
  };
  const _renderChart = useCallback(() => {
    return (
      <div className={cn(styles.boxBorder, styles.chart)}>
        <span className={styles.chart_title}>
          {chartTitle.title} ({chartTitle?.startDate} - {chartTitle?.endDate})
        </span>
        <Spin spinning={loadingEvent}>
          <div className={styles.chart_echarts}>
            {_.isEmpty(xAxis) ? (
              <EventEmpty style={{ paddingTop: 0 }} title="暂无数据" />
            ) : (
              <EventLine
                idName="overview-event"
                xAxis={xAxis}
                legend={legend}
                data={yAxis}
                color={["#3457C4", "#E85C36"]}
                events={checkedEvents}
                pointLegend={portfolioInfo.portfolioName}
                percent
              />
            )}
          </div>
        </Spin>
        <div className={styles.chart_table}>{_renderTab()}</div>
      </div>
    );
  }, [yAxis, portfolioInfo]);

  // 渲染组合和单基的列表
  const _renderTable = () => {
    const [eventList, setEventList] = useState([]);
    const [curEventCodes, setCurEventCode] = useState<string[]>();
    const [curFund, setCurFund] = useState();
    const [loadingSigTable, setLoadingSigTable] = useState(false);
    const [loadingComTable, setLoadingComTable] = useState(false);
    const callback = (key: string) => {
      setCurEventCode([]);
      setCurTab(key);
    };

    const handleChange = (e) => {
      setCurEventCode(e);
    };

    const handleChangeFund = (e) => {
      setCurFund(e);
    };

    useEffect(() => {
      if (curTab === "1") {
        handleQueryComEvent({
          eventCodes: curEventCodes?.length > 0 ? curEventCodes : undefined,
        });
      } else {
        handleQuerySigEvent({
          eventCodes: curEventCodes?.length > 0 ? curEventCodes : undefined,
          innerCode: curFund,
        });
      }
      handleQueryEventType({
        eventType: curTab === "1" ? "portfolio" : "fund",
      });
    }, [curTab, curEventCodes, curFund]);

    useEffect(() => {
      const domParent = document
        .getElementById("portfolio-table-scroll")
        .getElementsByClassName("ant-tabs-content-holder")[0]
        .getElementsByClassName(`hidden-table-scroll-${curTab}`)[0];
      const listenDom = domParent.getElementsByClassName("ant-table-body")[0];
      let timer = null;
      listenDom.onscroll = () => {
        domParent?.classList.remove("hidden-table-scroll");
        clearTimeout(timer);
        timer = setTimeout(() => {
          domParent?.classList.add("hidden-table-scroll");
        }, 1000);
      };
      // listenScroll(dom, `hidden-table-scroll`);
    }, [curTab, eventList]);

    // 补充表格数据
    const handlePatchData = (dataArr: any[] = []) => {
      let obj = { eventDate: PATCH_TEXT };
      const totalHeight = document.body.offsetHeight - 556;

      const minus =
        (totalHeight < 28 ? 280 : totalHeight) - dataArr.length * 29;
      let arr = [];
      if (minus > 0) {
        const count = Math.ceil(minus / 29);
        arr = new Array(count).fill(obj).map((v, i) => {
          // v.id = i
          return v;
        });
      }
      setTableData(dataArr.concat(arr));
    };

    // 查询组合事件
    const handleQueryComEvent = (params?: any) => {
      setLoadingComTable(true);
      queryPortfolioEventList({
        portfolioCode,
        ...params,
      }).then((res) => {
        setLoadingComTable(false);
        if (res?.code === "0") {
          handlePatchData(res?.data || []);
          // setTableData(res?.data || [])
          if (!_.isEmpty(res?.data)) {
            setCheckedEvents(res?.data?.slice(0, 5));
          }
        } else {
          handlePatchData([]);
        }
      });
    };

    // 查询单基事件
    const handleQuerySigEvent = (params?: any) => {
      setLoadingSigTable(true);
      queryFundEventList({
        portfolioCode,
        ...params,
      }).then((res) => {
        setLoadingSigTable(false);
        if (res?.code === "0") {
          handlePatchData(res?.data || []);
          // setTableData(res?.data || [])
        } else {
          // setTableData([])
          handlePatchData([]);
        }
      });
    };

    // 查询事件类型
    const handleQueryEventType = (params) => {
      queryFundByEventType(params).then((res: any) => {
        if (res?.code === "0") {
          const _resolveEventData = (data: any[]) => {
            // groupName, eventName
            const a = _.groupBy(data, "groupName");
            // console.log(a);
            const arr = [];

            // 处理三级
            const third = (secData) => {
              const d = _.groupBy(secData, "eventName");
              // console.log(d);
              let t = [];
              for (let key of Object.keys(d)) {
                console.log(d[key]);
                if (d[key].length > 1 || d[key][0].eventCodeName) {
                  t = t.concat([
                    {
                      title: key,
                      children: d[key],
                      parentCode: d[key][0].eventParentCode,
                    },
                  ]);
                } else {
                  t = t.concat(d[key]);
                }
              }
              return t;
            };

            for (let key of Object.keys(a)) {
              arr.push({
                title: key,
                // key,
                // level: 1,
                disabled: true,
                value: key,
                children: third(a[key]).map((v) => {
                  if (v.title) {
                    return {
                      title: v.title,
                      // key: v.title,
                      // level: 2,
                      value: v.parentCode,
                      children: v.children.map((m) => {
                        return {
                          title: m.eventCodeName,
                          // key: m.id,
                          value: m.eventCode,
                          // level: 3,
                        };
                      }),
                    };
                  } else {
                    return {
                      title: v.eventName,
                      // key: v.id,
                      value: v.eventCode,
                      // level: 2,
                    };
                  }
                }),
              });
            }
            console.log(arr);

            return arr;
          };
          const treeData = _resolveEventData(res?.data);
          setEventList(treeData);
        }
      });
    };

    const _renderSelect = () => {
      return (
        (<div style={{ display: "flex", paddingRight: 8 }}>
          {curTab === "2" && (
            <div className={cn(styles.tabSelect, styles.tabSelect1)}>
              <span
                className={cn(styles.tabSelect_label, styles.tabSelect1_label1)}
              >
                关联基金
              </span>
              <Select
                onChange={handleChangeFund}
                placeholder="请输入名称或代码"
                className={styles.cusSelect}
                allowClear
                value={curFund}
                popupClassName={styles.dropSelect}
              >
                {fundList?.map((v) => (
                  <Select.Option
                    label="全部"
                    key={v.code}
                    value={v.code}
                    title={`${v.name}(${v.secuCode})`}
                  >
                    {v.name}({v.secuCode})
                  </Select.Option>
                ))}
              </Select>
            </div>
          )}
          <div
            className={cn(
              styles.tabSelect,
              curTab === "2" ? styles.tabSelect2 : styles.tabSelectEvent
            )}
          >
            <span
              className={cn(
                styles.tabSelect_label,
                curTab === "2" && styles.tabSelect_label2
              )}
            >
              事件类型
            </span>
            <TreeSelect
              // className={styles.treeSelect}
              onChange={handleChange}
              value={curEventCodes}
              allowClear
              showSearch
              treeDefaultExpandAll
              treeData={eventList}
              dropdownMatchSelectWidth={false}
              multiple
              treeNodeFilterProp="title"
              popupClassName={styles.dropSelect}
            />
            {/* <Select
              mode="multiple"
              onChange={handleChange}
              className="findfit_select"
              allowClear
              value={curEventCodes}
              showSearch={false}
              placeholder="请选择"
            >
              {eventList?.map((v) => (
                <Select.Option
                  label="全部"
                  key={v.eventCode}
                  value={v.eventCode}
                >
                  {v.eventCodeName}
                </Select.Option>
              ))}
            </Select> */}
          </div>
        </div>)
      );
    };
    return (
      <div className={styles.eventList}>
        <span className={styles.eventList_title}>组合监控事项</span>
        <Tabs
          className={cn(styles.cusTab, styles.eventList_tab)}
          activeKey={curTab}
          onChange={callback}
          tabBarExtraContent={_renderSelect()}
          id="portfolio-table-scroll"
        >
          <TabPane tab="组合" key="1">
            <Table
              className={cn(
                styles.cusTable,
                styles.eventList_table,
                "hidden-table-scroll",
                "hidden-table-scroll-1"
              )}
              loading={loadingComTable}
              columns={combinationColumns}
              rowKey={(r) => r.id}
              dataSource={tableData}
              pagination={false}
              // scroll={{
              //   y:
              //     document.body.offsetHeight - 556 > 280
              //       ? document.body.offsetHeight - 560
              //       : document.body.offsetHeight - 556 < 25
              //       ? 280
              //       : 10 - tableData.length > 0
              //       ? document.body.offsetHeight - 560
              //       : 280,
              // }}
              scroll={{
                y:
                  document.body.offsetHeight - 556 > 280
                    ? document.body.offsetHeight - 560
                    : document.body.offsetHeight - 556 < 28
                    ? 280
                    : document.body.offsetHeight - 560,
              }}
            />
          </TabPane>
          <TabPane tab="单基" key="2">
            <Table
              className={cn(
                styles.cusTable,
                styles.eventList_table,
                "hidden-table-scroll",
                "hidden-table-scroll-2"
              )}
              loading={loadingSigTable}
              columns={singleColumns}
              dataSource={tableData}
              rowKey={(r) => r.id}
              pagination={false}
              // scroll={{
              //   y:
              //     document.body.offsetHeight - 556 > 280
              //       ? document.body.offsetHeight - 560
              //       : document.body.offsetHeight - 556 < 25
              //       ? 280
              //       : 10 - tableData.length > 0
              //       ? document.body.offsetHeight - 560
              //       : 280,
              // }}
              scroll={{
                y:
                  document.body.offsetHeight - 556 > 280
                    ? document.body.offsetHeight - 560
                    : document.body.offsetHeight - 556 < 28
                    ? 280
                    : document.body.offsetHeight - 560,
              }}
            />
          </TabPane>
        </Tabs>
      </div>
    );
  };

  // 判断右侧点评部分是否存在
  const notHaveReviewBlock =
    !isAuthored("EDIT_REVIEW") && !rightReveiw?.author && !rightReveiw?.comment;

  // console.log(notHaveReviewBlock);

  // 提交点评后查询最新点评时间
  const handleQueryLatestTime = () => {
    if (refOverviewDesc.current) {
      refOverviewDesc.current?.query();
    }
  };

  return (
    <PageWrapper narrow minWidth="1131px" style={{ paddingBottom: 0 }}>
      <Title style={{ marginLeft: 16, marginBottom: 12 }}>组合概览</Title>
      <div style={{ display: "flex" }}>
        <div className={styles.overviewPage_left}>
          <RenderDescOverview
            ref={refOverviewDesc}
            setPortfolioInfo={setPortfolioInfo}
          />
          {_renderChart()}
          {_renderTable()}
        </div>
        <div className={styles.overviewPage_right}>
          <Review
            queryLatestTime={handleQueryLatestTime}
            setRightReview={setRightReview}
          />
          <div
            // style={{
            //   height:
            //     (document.body.offsetHeight - 560 > 280
            //       ? document.body.offsetHeight - 170
            //       : tableData.length === 0
            //       ? document.body.offsetHeight - 170
            //       : document.body.offsetHeight - 560 < 25
            //       ? 373 + 294
            //       : 10 - tableData.length > 0
            //       ? 373 + document.body.offsetHeight - 560 + 12
            //       : 373 + 296) + (notHaveReviewBlock ? 106 : 0),
            //   marginTop: !notHaveReviewBlock ? 0 : -4,
            // }}
            style={{
              height:
                (document.body.offsetHeight - 560 > 280
                  ? document.body.offsetHeight - 172
                  : document.body.offsetHeight - 556 < 28
                  ? 373 + 296
                  : 373 + document.body.offsetHeight - 560 + 14) +
                (notHaveReviewBlock ? 106 : 0),
              marginTop: !notHaveReviewBlock ? 0 : -4,
            }}
          >
            <FundList
              eventCode={sigParams.eventCode}
              id={sigParams.id}
              innerCode={sigParams.innerCode}
              time={time}
              onDeleteTime={() => {
                setTime(null);
              }}
              createBy={portfolioInfo?.createdBy} //创建人信息
            ></FundList>
          </div>
        </div>
      </div>
    </PageWrapper>
  );
};

// const mapStateToProps = state => {
//   return state
// }

// export default connect(mapStateToProps, {})(PortfolioOverview)

export default PortfolioOverview;
